<template>
	<div class="table-box">
		<ProTable ref="proTable" :columns="columns" :requestApi="getUserList" :initParam="initParam">
			<!-- 表格 header 按钮 -->
			<template #tableHeader>
				<el-button type="primary" size="small" :icon="Plus" @click="openDrawer('新增')">新增字段</el-button>
			</template>
			<!-- 表格操作 -->
			<template #operation="scope">
				<el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
				<el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
			</template>
		</ProTable>
		<ColumnDrawer ref="drawerRef" />
	</div>
</template>

<script setup lang="ts" name="columnTable">
import { ref, reactive } from "vue";
import { User } from "@/api/interface";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ColumnDrawer from "./ColumnDrawer.vue";
import { Plus, Delete, EditPen } from "@element-plus/icons-vue";
import { getUserList, deleteUser, editUser, addUser, getUserGender } from "@/api/modules/user";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	id: ""
});

// 表格配置项
const columns: Partial<ColumnProps>[] = [
	{ type: "index", label: "#", width: 80 },
	{ prop: "name", label: "字段名称", width: 120, search: true },
	{ prop: "code", label: "字段标识", width: 120, search: true },
	{
		prop: "type",
		label: "字段类型",
		width: 120,
		sortable: true,
		search: false,
		searchType: "select",
		enum: getUserGender,
		searchProps: { label: "genderLabel", value: "genderValue" }
	},
	{
		prop: "createTime",
		label: "创建时间",
		width: 180,
		sortable: true,
		search: true,
		searchType: "datetimerange",
		searchInitParam: ["2022-08-30 00:00:00", "2022-08-20 23:59:59"]
	},
	{ prop: "operation", label: "操作", width: 180, fixed: "right" }
];

// 删除用户信息
const deleteAccount = async (params: User.ResUserList) => {
	await useHandleData(deleteUser, { id: [params.id] }, `删除【${params.username}】用户`);
	proTable.value.refresh();
};

const drawerRef = ref<DialogExpose>();
// const openDrawer = (title: string, rowData: Partial<User.ResUserList> = { avatar: "" }) => {
const openDrawer = (title: string, rowData: any = { avatar: "" }) => {
	let params = {
		title,
		rowData: { ...rowData },
		isView: title === "查看",
		apiUrl: title === "新增" ? addUser : title === "编辑" ? editUser : "",
		getTableList: proTable.value.refresh
	};
	drawerRef.value!.acceptParams(params);
};
</script>
